package api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.json.JSONUtil;
import common.ApplicationVariable;
import lombok.SneakyThrows;
import model.ResultData;
import model.UserInfo;
import util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * 登录接口
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType(ApplicationVariable.RESPONSE_CONTENT_TYPE);
        int state = -1;
        String data = "";
        String msg = "未知错误！";
        // 1.得到前端参数并效验
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String isadmin = req.getParameter("isadmin");
        if (!StrUtil.isBlank(username) && !StrUtil.isBlank(password)) {
            // 2.请求数据库验证用户名和密码
            Connection connection = DBUtil.getConnection();
            String sql = "select * from userinfo where username=? and password=?";
            if (!StrUtil.isBlank(isadmin)) { // 超管登录
                sql += " and isadmin=1";
            }
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setString(1, username);
            statement.setString(2,
                    MD5.create().digestHex(password)); // 数据库是加密的密码
            ResultSet resultSet = statement.executeQuery();
            if (resultSet.next()) {
                // 用户名和密码正确
                state = 200;
                data = username;
                msg = "";
                // 将当前登陆用户保存到 session 中
                HttpSession session = req.getSession(true);
                UserInfo userInfo = new UserInfo();
                userInfo.setUid(resultSet.getInt("uid"));
                userInfo.setUsername(resultSet.getString("username"));
                session.setAttribute(ApplicationVariable.SESSION_USER_KEY, userInfo);
            } else {
                msg = "用户名或密码错误！";
            }
        } else {
            msg = "非法参数！";
        }
        // 3.将结果返回给前端
        ResultData resultData = new ResultData();
        resultData.setState(state);
        resultData.setData(data);
        resultData.setMsg(msg);
        resp.getWriter().println(JSONUtil.toJsonStr(resultData));
    }
}
